<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自适应单图片展示</title>
    <!-- 引入Bootstrap CSS -->
    <link href="./bootstrap.min.css" rel="stylesheet">
    
    <style>
        /* 页面基础样式 */
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            background-color: #f8f9fa;
            display: flex;
            flex-direction: column;
        }
        
        /* 图片容器样式 - 确保响应式布局 */
        .image-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 1rem;
            box-sizing: border-box;
            width: 100%;
        }
        
        /* 图片包装器 */
        .image-wrapper {
            position: relative;
            display: inline-block;
            cursor: pointer;
        }
        
        /* 自适应图片样式 - 增强响应式支持 */
        .adaptive-image {
            max-width: 100%;
            max-height: 90vh; /* 限制最大高度为视口的90% */
            height: auto;
            width: auto;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            border-radius: 6px;
            transition: all 0.3s ease;
            /* 确保在小屏幕上正确缩放 */
            object-fit: contain;
        }
        
        /* 按钮容器样式 */
        .button-container {
            margin-top: 20px;
            text-align: center;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
        }
        
        /* 在小屏幕上调整按钮间距和布局 */
        @media (max-width: 480px) {
            .button-container {
                flex-direction: column;
                align-items: center;
                gap: 12px;
            }
            
            .download-btn {
                margin-left: 0 !important;
                width: 100%;
                max-width: 200px;
            }
            
            .random-goddess-btn {
                width: 100%;
                max-width: 200px;
            }
        }
        
        /* 随机女神按钮样式 */
        .random-goddess-btn {
            font-size: 16px;
            padding: 10px 20px;
            transition: all 0.3s ease;
            border-radius: 25px; /* 圆角按钮 */
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            font-weight: 500;
        }
        
        /* 随机女神按钮悬停效果 */
        .random-goddess-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 123, 255, 0.2);
        }
        
        /* 随机女神按钮点击效果 */
        .random-goddess-btn:active {
            transform: translateY(0);
        }
        
        /* 下载按钮样式 */
        .download-btn {
            margin-left: 10px;
            font-size: 16px;
            padding: 10px 20px;
            border-radius: 25px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        /* 下载按钮悬停效果 */
        .download-btn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(25, 135, 84, 0.2);
        }
        
        /* 下载按钮点击效果 */
        .download-btn:active:not(:disabled) {
            transform: translateY(0);
        }
        
        /* 下载按钮禁用状态 */
        .download-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        /* 下载按钮响应式调整 */
        @media (max-width: 768px) {
            .download-btn {
                font-size: 14px;
                padding: 8px 16px;
                margin-left: 8px;
            }
        }
        
        @media (max-width: 576px) {
            .download-btn {
                font-size: 13px;
                padding: 7px 14px;
                margin-left: 5px;
            }
        }
        
        /* 爱心动画样式 */
        .heart-animation {
            position: absolute;
            width: 50px;
            height: 50px;
            background-color: transparent;
            font-size: 40px;
            color: #ff4d6d;
            pointer-events: none;
            opacity: 0;
            transform: translate(-50%, -50%) scale(0);
            transition: all 0.3s ease;
            z-index: 1000;
        }
        
        .heart-animation::before,
        .heart-animation::after {
            content: '❤️';
            position: absolute;
            width: 100%;
            height: 100%;
            text-align: center;
            line-height: 50px;
        }
        
        .heart-animation.show {
            opacity: 1;
            animation: heart-animation 1.5s ease-in-out forwards;
        }
        
        @keyframes heart-animation {
            0% {
                opacity: 0;
                transform: translate(-50%, -50%) scale(0);
            }
            50% {
                opacity: 1;
                transform: translate(-50%, -50%) scale(1.2);
            }
            100% {
                opacity: 0;
                transform: translate(-50%, -50%) scale(1) translateY(-30px);
            }
        }
        
        /* 响应式调整 - 针对不同屏幕尺寸 */
        @media (max-width: 768px) {
            .image-container {
                padding: 0.5rem;
            }
            
            .adaptive-image {
                max-height: 85vh; /* 在小屏幕上给更多空间给页脚 */
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 小屏幕上使用更轻微的阴影 */
            }
            
            .random-goddess-btn {
                font-size: 14px;
                padding: 8px 16px;
            }
            
            .heart-animation {
                width: 40px;
                height: 40px;
                font-size: 32px;
            }
        }
        
        /* 图片加载动画 */
        .loading {
            text-align: center;
            padding: 2rem;
            min-height: 200px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        
        .spinner {
            width: 3rem;
            height: 3rem;
            border: 0.3rem solid rgba(0, 123, 255, 0.2);
            border-radius: 50%;
            border-top-color: #0d6efd;
            animation: spin 1s ease-in-out infinite;
            margin: 0 auto 1rem;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 简单的页脚样式 */
        footer {
            background-color: #343a40;
            color: white;
            text-align: center;
            padding: 0.75rem 0;
            margin-top: auto;
            font-size: 0.9rem;
        }
        
        /* 小屏幕上简化页脚 */
        @media (max-width: 576px) {
            footer {
                padding: 0.5rem 0;
                font-size: 0.8rem;
            }
            
            .random-goddess-btn {
                font-size: 13px;
                padding: 7px 14px;
            }
            
            .heart-animation {
                width: 35px;
                height: 35px;
                font-size: 28px;
            }
        }
    </style>
</head>
<body>
	<div id = "vue">
		<!-- 导航栏 -->
		<!-- <nav class="navbar navbar-dark bg-primary mb-0">
		    <div class="container">
		        <a class="navbar-brand" href="#">
		            自适应图片展示
		        </a>
		    </div>
		</nav> -->
		
		<!-- 主要内容区 - 图片容器 -->
        <div class="image-container">
            <!-- 图片加载状态 -->
            <div v-if="isLoading" class="loading">
                <div class="spinner"></div>
                <p>加载图片中...</p>
            </div>
            <div v-else-if="error" class="loading">
                <p class="text-danger mb-3">图片加载失败</p>
                <button class="btn btn-primary" @click="retryLoadImage">
                    重新加载
                </button>
            </div>
            
            <!-- 图片将在这里显示和随机女神按钮 -->
            <div v-else>
                <div class="image-wrapper" @click="handleLike">
                    <img class="adaptive-image" :src="mainImageSrc" alt="自适应图片" @load="onImageLoad" @error="onImageError">
                    <!-- 爱心动画容器 -->
                    <div class="heart-animation" :class="{show: showHeart}" ref="heartElement"></div>
                </div>
                <div class="button-container">
                    <button class="btn btn-primary random-goddess-btn" @click="getDescription('随机女神')">
                        随机女神
                    </button>
                    <button class="btn btn-primary random-goddess-btn" @click="getDescription('随机帅哥')">
                        随机帅哥
                    </button>
                    <button class="btn btn-primary random-goddess-btn" @click="getDescription('随机动漫')">
                        随机动漫
                    </button>
                    <button class="btn btn-primary random-goddess-btn" @click="getDescription('随机风景')">
                        随机风景
                    </button>
                    <button class="btn btn-success download-btn" @click="downloadImage" :disabled="isLoading || error">
                        下载图片
                    </button>
                </div>
            </div>
        </div>
		
		<!-- 页脚 -->
		<footer>
		    <div class="container">
		        <p class="mb-0">调整窗口大小查看图片自适应效果</p>
		    </div>
		</footer>
	</div>
    

    <!-- 引入Bootstrap JS -->
    <script src="./bootstrap.bundle.min.js"></script>
    
	<script type="text/javascript" src="../vue/vue.min.js"></script>
	<link href="../vue/element/index.css" rel="stylesheet">
	<script type="text/javascript" src="../vue/element/index.js"></script>
	<script type="text/javascript" src="../js/jquery.min.js"></script>
	<script type="text/javascript" src="../js/bootstrap.min.js"></script>
	<script type="text/javascript" src="../js/perfect-scrollbar.min.js"></script>
	<script type="text/javascript" src="../js/main.min.js"></script>
	
	<!--消息提示-->
	<script src="../js/bootstrap-notify.min.js"></script>
	<script type="text/javascript" src="../js/lightyear.js"></script>
	
	<script type="text/javascript" src="../vue/vue_config.js"></script>
	<script type="text/javascript" src="../vue/axios.min.js"></script>
	<script type="text/javascript" src="../vue/vue_api.js"></script>
	<script type="text/javascript" src="../vue/commons.js"></script>
	<script type="text/javascript">
		new Vue({
			el: '#vue',
			data: {
				mainImageSrc: "",
				isLoading: true,
				error: false,
				autoRetryCount: 0, // 自动重试计数
				showHeart: false ,// 控制爱心动画显示
                type: '',
			},
			created() {
				console.log("created")
				window.addEventListener('resize', this.adjustImage);
				this.getDescription('随机女神');
			},
			beforeDestroy() {
				// 清理事件监听器，防止内存泄漏
				window.removeEventListener('resize', this.adjustImage);
			},

			methods: {
					
					//共用
					async getDescription( type ){
					    this.type = type;
                        var url = rootUrl+"freeapi/randomGodess";
					    console.log("getDescription",type)
                        if(type == '随机女神'){
                            console.log("没有内容")
                            url = rootUrl+"freeapi/randomGodess";
                        }else{
                            console.log("有内容"+type)
                            url = rootUrl+"freeapi/randomTu?type="+type;
                        }
						try {
							this.isLoading = true;
							this.error = false;
							await fetchDataGet(url).then(res =>{
								if(res.code === 200){
								    
									this.mainImageSrc = res.message;
								    console.log(this.mainImageSrc);
								    this.isLoading = false; // 关键修改：图片URL获取成功后将加载状态设为false
								}else{
									this.error = true;
									this.isLoading = false;
									danger(res.message || '获取图片信息失败');
								}
							})
						} catch (err) {
							this.error = true;
							this.isLoading = false;
							console.error('获取图片失败:', err);
							danger('获取图片失败，请稍后重试');
						}
				},
				
				// 重试加载图片
				retryLoadImage() {
					console.log('尝试重新加载图片...');
					this.mainImageSrc = ''; // 清空图片源以触发重新加载
					this.getDescription(this.type); // 重新获取图片
				},
				
				// 处理点赞
				handleLike(event) {
					// 打印点赞信息
					console.log("点赞了一次");
					
					// 显示爱心动画
					this.showHeart = true;
					
					// 设置心形位置
					const heartElement = this.$refs.heartElement;
					if (heartElement) {
						const rect = this.$el.querySelector('.image-wrapper').getBoundingClientRect();
						const x = event.clientX - rect.left;
						const y = event.clientY - rect.top;
						heartElement.style.left = `${x}px`;
						heartElement.style.top = `${y}px`;
					}
					
					// 1.5秒后隐藏爱心
					setTimeout(() => {
						this.showHeart = false;
					}, 1500);
				},
				
				// 下载图片
				downloadImage() {
					if (!this.mainImageSrc) {
						console.error('没有可下载的图片');
						alert('没有可下载的图片');
						return;
					}
					
					try {
						// 创建一个临时的下载链接
						const link = document.createElement('a');
						link.href = this.mainImageSrc;
						
						// 设置文件名 - 使用时间戳作为唯一标识
						const timestamp = new Date().getTime();
						const filename = `goddess_${timestamp}.jpg`;
						link.download = filename;
						
						// 为了兼容性，设置target
						link.target = '_blank';
						
						// IE11兼容处理
						if (window.navigator && window.navigator.msSaveOrOpenBlob) {
							// 对于IE，使用msSaveOrOpenBlob方法
							this.downloadImageWithFetch();
							return;
						}
						
						// 触发点击事件
						document.body.appendChild(link);
						
						// 使用setTimeout确保异步执行
						setTimeout(() => {
							link.click();
							// 清理临时元素
							setTimeout(() => {
								document.body.removeChild(link);
							}, 100);
						}, 0);
						
						console.log(`图片下载成功: ${filename}`);
						
					} catch (error) {
						console.error('图片下载失败:', error);
						// 如果直接下载失败，尝试使用fetch方式
						this.downloadImageWithFetch();
					}
				},
				
				// 使用fetch方式下载图片（兼容更多浏览器）
				downloadImageWithFetch() {
					if (!this.mainImageSrc) return;
					
					fetch(this.mainImageSrc)
						.then(response => {
							if (!response.ok) throw new Error('Network response was not ok');
							return response.blob();
						})
						.then(blob => {
							// 创建blob URL
							const url = window.URL.createObjectURL(blob);
							const link = document.createElement('a');
							link.href = url;
							
							// 设置文件名
							const timestamp = new Date().getTime();
							const filename = `goddess_${timestamp}.jpg`;
							link.download = filename;
							
							// 触发点击
							document.body.appendChild(link);
							link.click();
							
							// 清理
							setTimeout(() => {
								document.body.removeChild(link);
								window.URL.revokeObjectURL(url);
							}, 100);
							
							console.log(`使用fetch方式下载成功: ${filename}`);
						})
						.catch(error => {
							console.error('fetch下载失败:', error);
							alert('图片下载失败，请稍后重试');
						});
				},

				onImageLoad() {
				    this.isLoading = false;
				    this.adjustImage(); // 初始调整
				},
				
				onImageError() {
					this.isLoading = false;
					this.error = true;
					console.error('图片加载失败');
					// 添加可选的自动重试逻辑
					if (this.autoRetryCount < 2) { // 最多自动重试2次
						this.autoRetryCount++;
						console.log(`自动重试第${this.autoRetryCount}次...`);
						setTimeout(() => this.retryLoadImage(), 1000);
					}
				},
	
				adjustImage() {
				    const container = document.querySelector('.image-container');
				    const containerWidth = container.clientWidth;
				    const containerHeight = container.clientHeight;
				    const imgElement = document.querySelector('.adaptive-image');
				    
				    // 可以根据需要添加额外的调整逻辑
				    console.log(`容器尺寸: ${containerWidth}x${containerHeight}`);
				    if (imgElement) {
				        console.log(`图片尺寸: ${imgElement.offsetWidth}x${imgElement.offsetHeight}`);
				    }
				},
			}
	
		})
	</script>
</body>
</html>